import config from '../../utils/config';

const defaultAvatarUrl = config.defaultAvatarUrl

Page({
  data: {
    userInfo: {
      avatar: defaultAvatarUrl,
      name: ''
    }
  },

  onLoad() {
    const token = wx.getStorageSync('token');
    const cacheUserInfo = wx.getStorageSync('userInfo');

    if (!token) {
      return wx.navigateTo({ url: '/pages/login/login' });
    }

    if (cacheUserInfo) {
      this.setUserInfo(cacheUserInfo);
    } else {
      this.fetchUserInfo(token);
    }
  },

  setUserInfo(userInfo) {
    this.setData({
      userInfo: {
        avatar: userInfo.avatar || defaultAvatarUrl,
        name: userInfo.name || ''
      }
    });
  },

  fetchUserInfo(token) {
    wx.request({
      url: `${config.baseUrl}/getUserInfo`,
      method: 'GET',
      header: { Authorization: token },
      success: (res) => {
        if (res.data && res.data.code === 200) {
          this.setUserInfo(res.data.data);
        } else {
          this.handleRequestError('获取用户信息失败', res);
        }
      },
      fail: (err) => this.handleRequestError('请求用户信息失败', err)
    });
  },

  handleRequestError(message, error) {
    console.error(message, error);
    this.setUserInfo({});
  },

  onInputChange(e) {
    this.setData({ 'userInfo.name': e.detail.value });
  },

  onChooseAvatar(e) {
    this.setData({ 'userInfo.avatar': e.detail.avatarUrl });
  },

  onSave() {
    const { avatar, name } = this.data.userInfo;

    if (!this.isValidName(name)) {
      return wx.showToast({ title: '昵称长度应为1-15个字符', icon: 'none' });
    }

    const cacheUserInfo = wx.getStorageSync('userInfo');
    if (avatar === cacheUserInfo.avatar) {
      this.saveUserInfo(avatar, name);
    } else {
      this.uploadAvatarAndSave(avatar, name);
    }
  },

  isValidName(name) {
    return name && name.length >= 1 && name.length <= 15;
  },

  uploadAvatarAndSave(avatar, name) {
    wx.uploadFile({
      url: `${config.baseUrl}/uploadAvatar`,
      filePath: avatar,
      name: 'avatar',
      header: { 'Authorization': wx.getStorageSync('token') },
      success: (uploadRes) => {
        const data = JSON.parse(uploadRes.data);
        if (data.code === 200) {
          this.saveUserInfo(data.data.avatar, name);
        } else {
          this.showErrorToast('头像上传失败');
        }
      },
      fail: () => this.showErrorToast('头像上传失败')
    });
  },

  saveUserInfo(avatar, name) {
    wx.request({
      url: `${config.baseUrl}/setUserInfo`,
      method: 'POST',
      header: {
        'Authorization': wx.getStorageSync('token'),
        'Content-Type': 'application/json'
      },
      data: { avatar, name },
      success: (res) => {
        if (res.statusCode === 200) {
          wx.setStorageSync('userInfo', { avatar, name });
          wx.showToast({ title: '保存成功', icon: 'success' });
          wx.reLaunch({ url: '/pages/profile/profile' });
        } else {
          this.showErrorToast('保存失败');
        }
      },
      fail: () => this.showErrorToast('请求失败')
    });
  },

  showErrorToast(message) {
    wx.showToast({ title: message, icon: 'error' });
  },

  onLogout: function() {
    wx.showToast({
      title: '已退出登录',
      icon: 'none'
    });

    // 清除所有缓存
    wx.clearStorageSync();

    // 跳转到首页
    wx.reLaunch({
      url: '/pages/index/index'
    });
  }
});